package demo.sort;

import com.alibaba.fastjson.JSON;

/**
 * @Author: admin
 * @Description:
 * @Date: Create in 2021/6/6-15:48
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 4, 7, 8, 3, 6, 9};
        sort(arr);
        System.out.println(JSON.toJSONString(arr));
    }

    static void swap(int[] arr, int i, int pos) {
        int temp = arr[i];
        arr[i] = arr[pos];
        arr[pos] = temp;
    }

    public static void sort(int[] arr) {
        sort(arr, 0, arr.length - 1);
    }

    public static void sort(int[] arr, int left, int right) {
        if (left == right) {
            return;
        }
        int mid = left + (right - left) / 2;
        sort(arr, left, mid);
        sort(arr, mid+1, right);
        merge(arr, left, mid+1, right);

    }

    ;


    static void merge(int[] arr, int leftPtr, int rightPtr, int rightBound) {
        int[] temp = new int[rightBound - leftPtr + 1];
        int mid = rightPtr - 1;
        int i = leftPtr;
        int j = rightPtr;
        int k = 0;
        while (i <= mid && j <= rightBound) {
            temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
        }
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= rightBound) {
            temp[k++] = arr[j++];
        }
        System.arraycopy(temp, 0, arr, leftPtr, temp.length);

    }

}
